package com.zh.freechat.domain.user.repository.real;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zh.freechat.domain.user.entity.UserRelId;
import com.zh.freechat.domain.user.entity.UserRelationFriend;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author Zhou
 * @date 20:23 2024/3/31
 */
@Mapper
public interface UserRelationFriendMapper extends BaseMapper<UserRelationFriend> {

    /**
     * 移除好友关系
     * 如果user1=userId，就removed user1
     * 如果user2=userId，就removed user2
     *
     * @param userId 要removed的一方
     * @param user1
     * @param user2
     */
    @Update(value = """
            UPDATE ch_user_friend 
             SET removed_u1= CASE (user1=#{userId}) WHEN true THEN 1 ELSE removed_u1 END 
             ,removed_u2= CASE (user2=#{userId}) WHEN true THEN 1 ELSE removed_u2 END 
            WHERE (user1=#{user1} AND user2=#{user2}) ;
            """)
    void removeByUserId(@Param("userId") String userId, @Param("user1") String user1, @Param("user2") String user2);

    @Select({"""
            <script>
                SELECT id, user1, user2 
                FROM ch_user_friend 
                WHERE ( (user1 IN 
                            <foreach item='userId' collection='userIds' open='(' separator=',' close=')'>
                                #{userId}
                            </foreach> 
                            AND user2 = #{userId2}
                        ) 
                        OR 
                        (user2 IN 
                            <foreach item='userId' collection='userIds' open='(' separator=',' close=')'>
                                #{userId}
                            </foreach> 
                            AND user1 = #{userId2}
                        )
                    ) AND (removed_u1 = 0 AND removed_u2 = 0)
            </script>
            """})
    List<UserRelId> findRelIdByBothUserId(@Param("userIds") List<String> userIds, @Param("userId2") String userId2);

    @Select(value = "SELECT id,user1,user2 FROM ch_user_friend ")
    List<UserRelId> findRelIdAll();

    /**
     * 是不是好友关系(双向好友)
     *
     * @param user1Id
     * @param user2Id
     * @return
     */
    @Select(value = "SELECT COUNT(*) FROM ch_user_friend WHERE (user1=#{user1Id} AND user2=#{user2Id}) and removed_u1=0 and removed_u2=0 ")
    int existsFriendRelation(@Param("user1Id") String user1Id, @Param("user2Id") String user2Id);

}
